package admin

import (
	"github.com/gin-gonic/gin"
	"goadmin/models"
	"strconv"
)

type CofigController struct {
	BaseController
}

func (con CofigController) Index(c *gin.Context) {
	configList := []models.Config{}
	pageInfo, _ := c.Get("pageRequest")
	pageData := pageInfo.(gin.H)
	var total int64
	models.DB.Model(&models.Config{}).Count(&total)
	models.DB.Offset(pageData["offset"].(int)).Limit(pageData["pageSize"].(int)).Find(&configList)
	con.pageSuccess(c, configList, total)
}

func (con CofigController) UpdateConfig(c *gin.Context) {
	idStr := c.Param("id")         // ① 取字符串
	id, err := strconv.Atoi(idStr) // ② 转 int
	if err != nil {
		con.errorMessage(c, "Id有误", 201)
		return
	}
	var req struct {
		ParamsKey   string  `binding:"required" json:"params_key"`
		ParamsValue float32 `binding:"required" json:"params_value"`
		Description string  `binding:"required" json:"description"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		con.errorMessage(c, err.Error(), 201)
		return
	}
	updateData := map[string]interface{}{
		"ParamsKey":   req.ParamsKey,
		"ParamsValue": req.ParamsValue,
		"Description": req.Description,
	}
	result := models.DB.Model(&models.Config{}).Where("id = ?", id).Updates(updateData)
	if result.RowsAffected == 0 {
		con.errorMessage(c, "数据未更新", 201)
		return
	}
	con.successMessage(c, "更新成功", nil)
}
